package org.linuxsogood.boot.grpc.server;

import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import org.linuxsogood.boot.grpc.MetricsServiceGrpc;
import org.linuxsogood.boot.grpc.StreamingExample;
import org.lognet.springboot.grpc.GRpcService;

/**
 * @author liu.hongwei
 * @since 2020/11/17 17:54
 */
@GRpcService
@Slf4j
public class MetricsServiceImpl extends MetricsServiceGrpc.MetricsServiceImplBase {

    @Override
    public StreamObserver<StreamingExample.Metric> collect(StreamObserver<StreamingExample.Average> responseObserver) {
        return new StreamObserver<StreamingExample.Metric>() {
            private long sum = 0;
            private long count = 0;

            @Override
            public void onNext(StreamingExample.Metric value) {
                log.info("value:{}", value);
                sum += value.getMetric();
                count++;
            }

            @Override
            public void onError(Throwable t) {
                responseObserver.onError(t);
            }

            @Override
            public void onCompleted() {
                responseObserver.onNext(StreamingExample.Average.newBuilder().setVal(sum/count).build());
            }
        };
    }
}
